package com.freesun.shop.config;




import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.freesun.shop.entity.User;
import com.freesun.shop.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;


@Configuration
public class UserRealm extends AuthorizingRealm {
    private static String WX_LOGIN_URL
            ="https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Value("${wx.appid}")
    private String wxAppId;
    @Value("${wx.secret}")
    private String wxSecret;

    @Autowired //spring提供发起请求的
    private RestTemplate restTemplate;
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String wxCode = token.getPrincipal().toString();
        String openid = getOpenidByCode(wxCode);
        User user= userService.findUserByUsername(openid);
        //该用户不存在，会自动创建用户
        if (null == user){
            user = userService.regeister(openid);

        }
        return new SimpleAuthenticationInfo(user,"WX_LOGIN",wxCode);
    }

    private String getOpenidByCode(String wxCode) {
        //使用code给微信服务器发送请求
        String url = String.format(WX_LOGIN_URL, wxAppId, wxSecret, wxCode);
        String wxResult = restTemplate.getForObject(url, String.class);
        JSONObject json = JSONUtil.parseObj(wxResult);
        if (json.containsKey("errcode")) { //解析包含错误节点，表示该次请求错误
            Long errcode = json.get("errcode", Long.class);
            if(errcode==40029){
                throw new AuthenticationException("微信传来的code错误");
            }
        }
        return json.get("openid", String.class);
    }
}
